package com.example.takephotovideo.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.example.takephotovideo.customview.headview.HeadCustomView;
import com.example.takephotovideo.takephotovideo.PhotoVideoListBean;
import com.example.takephotovideo.utils.FileUtil;
import com.example.takephotovideo.utils.MyGlideEngine;
import com.example.takephotovideo.utils.PathUtils;
import com.example.takephotovideo.R;
import com.example.takephotovideo.customview.TakePhotoView;
import com.example.takephotovideo.base.BaseActivity;
import com.example.takephotovideo.utils.UUIDUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class TakePhotoVideoActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, TakePhotoView.OnItemClickListener {
    private TextView btSelete;
    private int REQUEST_CODE_CHOOSE = 10086;
    private static final int PRC_PHOTO_PREVIEW = 10010;
    private TakePhotoView takephotoview;
    private HeadCustomView title;
    private int surplus;
    String[] perms = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btSelete = findViewById(R.id.bt_selete);
        title = findViewById(R.id.title);
        takephotoview = findViewById(R.id.takephotoview);
        title.setTextTitle("选择图片或视频");
        title.setIvBackGone();
        takephotoview.setOnItemClickListener(this);
        btSelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String path = "";
                for (int i = 0; i < takephotoview.getFileList().size(); i++) {
                    path = path + takephotoview.getFileList().get(i).getFileurl() + "\n";
                }
                btSelete.setText(path);

            }
        });
    }
    //请求码
    @AfterPermissionGranted(PRC_PHOTO_PREVIEW)
    private void methodRequiresTwoPermission() {
        if (EasyPermissions.hasPermissions(this, perms)) {
            /**
             *  选择视频和图片
             *  .choose(MimeType.ofAll())
             *  选择图片
             *  .choose(MimeType.ofImage())
             *  选择视频
             *  .choose(MimeType.ofVideo())
             *  自定义选择选择的类型
             *  .choose(MimeType.of(MimeType.JPEG, MimeType.PNG, MimeType.MP4))
             */
            Matisse.from(TakePhotoVideoActivity.this)
                    //选择视频和图片
                    .choose(MimeType.ofAll(), false)
                    //有序选择图片 123456...
                    .countable(true)
                    //最大选择数量为9
                    .maxSelectable(surplus)
                    //是否只显示选择的类型的缩略图，就不会把所有图片视频都放在一起，而是需要什么展示什么
                    .showSingleMediaType(true)
                    //选择方向
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    //这两行要连用 是否在选择图片中展示照相 和适配安卓7.0 FileProvider
                    .capture(true)
                    .captureStrategy(new CaptureStrategy(true, "PhotoPicker"))
                    //蓝色主题
                    .theme(R.style.Matisse_Zhihu)
                    //黑色主题
//                    .theme(R.style.Matisse_Dracula)
                    //界面中缩略图的质量
                    .thumbnailScale(0.85f)
                    //Glide加载方式
                    .imageEngine(new MyGlideEngine())
                    .forResult(REQUEST_CODE_CHOOSE);
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "选择图片需要以下权限:", PRC_PHOTO_PREVIEW, perms);
        }
    }

    /**
     * 拒绝权限前往设置中开启权限的回调
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            methodRequiresTwoPermission();
        } else if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            List<PhotoVideoListBean> fileListBeans = new ArrayList<>();
            for (int i = 0; i < mSelected.size(); i++) {
                try {
                    if ("mp4".equals(FileUtil.getFileType(PathUtils.getPath(this, mSelected.get(i))
                    ))) {
                        fileListBeans.add(new PhotoVideoListBean(PathUtils.getPath(this, mSelected.get(i)), true,UUIDUtils.getRandomNumNumber()));
                    } else {
                        fileListBeans.add(new PhotoVideoListBean(PathUtils.getPath(this, mSelected.get(i)), false,UUIDUtils.getRandomNumNumber()));
                    }
                } catch (Exception e) {
                }
            }
            takephotoview.setDataList(fileListBeans);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // EasyPermissions 权限处理请求结果
        Log.i("DDD", "onRequestPermissionsResult:" + requestCode);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    //同意授权
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Log.d("DDD", "onPermissionsGranted:" + requestCode + ":" + perms.size());
    }

    //拒绝授权
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Log.d("DDD", "onPermissionsDenied:" + requestCode + ":" + perms.size());
        new AppSettingsDialog.Builder(this)
                .setTitle("提醒")
                .setRationale("此app需要这些权限才能正常使用")
                .build()
                .show();
    }

    /**
     * 回调出来还可以选择的图片的张数
     */
    @Override
    public void addPhotoVideo(int surplu) {
        surplus = surplu;
        methodRequiresTwoPermission();
    }
}
